#define  _CRT_SECURE_NO_WARNINGS 1
#include "Slist.h"

void SListPrint(SListNode* ps)
{
	SListNode* curr = ps;
	while (curr)
	{
		printf("%d -> ", curr->_data);
		curr = curr->_next;
	}
	printf("NULL\n");
}
SListNode* BuyListNode(SListDataType data)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL)
	{
		printf("malloc fail\n");
		exit(1);
	}
	newnode->_data = data;
	newnode->_next = NULL;
	return newnode;
}

void SListPushBack(SListNode** ps, SListDataType data)
{
	assert(ps);
	if (*ps == NULL)
	{
		*ps = BuyListNode(data);
	}
	else
	{
		SListNode* curr = *ps;
		while (curr->_next)
			curr = curr->_next;
		SListNode* newnode = BuyListNode(data);
		curr->_next = newnode;
	}

}
void SListPushFront(SListNode** ps, SListDataType data)
{
	assert(ps);
	SListNode* newnode = BuyListNode(data), * head = *ps;
	newnode->_next = head;
	*ps = newnode;
}

void SListPopBack(SListNode** ps)
{
	assert(ps);

	if (*ps == NULL)
		return;
	else if ((*ps)->_next == NULL)
	{
		SListNode* head = *ps;
		free(head);
		*ps = NULL;
	}
	else
	{
		SListNode* head = *ps;
		while (head->_next->_next)
			head = head->_next;
		free(head->_next);
		head->_next = NULL;
	}
}
void SListPopFront(SListNode** ps)
{
	assert(ps);

	if (*ps == NULL)
		return;
	SListNode* head = *ps;
	*ps = head->_next;
	free(head);
}


SListNode* SListFind(SListNode* ps, SListDataType data)
{
	SListNode* curr = ps;
	while (curr)
	{
		if (curr->_data == data)
			return curr;
		curr = curr->_next;
	}
	return NULL;
}

void SListInsert(SListNode** ps, SListNode* pos, SListDataType data)
{
	assert(ps);
	assert(pos);

	SListNode* curr = *ps;
	if (curr == pos)
		SListPushFront(ps, data);
	else
	{
		while (curr->_next != pos)
			curr = curr->_next;
		SListNode* newnode = BuyListNode(data);
		curr->_next = newnode;
		newnode->_next = pos;
	}
}
void SListErase(SListNode** ps, SListNode* pos)
{
	assert(pos);
	assert(ps);
	assert(*ps);
	SListNode* curr = *ps;
	if (curr == pos)
		SListPopFront(ps);
	else
	{
		while (curr->_next != pos)
			curr = curr->_next;
		curr->_next = pos->_next;
		free(pos);
	}
}

void SListInsertAfter(SListNode* pos, SListDataType data)
{
	assert(pos);
	SListNode* next = pos->_next;
	SListNode* newnode = BuyListNode(data);
	pos->_next = newnode;
	newnode->_next = next;
}
void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->_next);

	SListNode* del = pos->_next;
	SListNode* next = del->_next;
	pos->_next = next;
	free(del);
}